package com.ccc.influxdb.util;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;

/**
 * @author superC
 * @version 2.0.0
 * @date 2023/2/23
 */

public class MyDateUtil {

    public static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";

    public static final String DEFAULT_PATTERN_UTC = "yyyy-MM-dd'T'HH:mm:ss'Z'";

    public static final DateTimeFormatter DEFAULT_FORMATTER = DateTimeFormatter.ofPattern(DEFAULT_PATTERN);

    public static final DateTimeFormatter DEFAULT_FORMATTER_UTC = DateTimeFormatter.ofPattern(DEFAULT_PATTERN_UTC);

    /**
     * 标准时间字符串转换为UTC格式时间字符串
     * @param timeStr 标准时间字符串，格式为 yyyy-MM-dd HH:mm:ss
     * @return UTC格式时间字符串 yyyy-MM-ddTHH:mm:ssZ
     */
    public static String stringToUTC(String timeStr) {
        return stringToLDT(timeStr).minusHours(8).format(DEFAULT_FORMATTER_UTC);
    }

    public static String utcToString(String utcStr) {
        return stringToLDT(utcStr, DEFAULT_PATTERN_UTC).plusHours(8).format(DEFAULT_FORMATTER);
    }

    public static long stringToTimestamp(String timeStr) {
        return ldtToInstant(stringToLDT(timeStr)).toEpochMilli();
    }

    public static String instantToString(Instant instant) {
//        return instantToLDT(instant).minusHours(8).format(DEFAULT_FORMATTER);
        return instantToLDT(instant).format(DEFAULT_FORMATTER);
    }

    /**
     * 将某时间字符串转为自定义时间格式的LocalDateTime
     *
     * @param timeStr 时间字符串
     * @param format  自定义时间格式
     * @return {@link LocalDateTime}
     * @date 2023/2/28 13:53
     * @author superC
     */
    public static LocalDateTime stringToLDT(String timeStr, String format) {
        return LocalDateTime.parse(timeStr, DateTimeFormatter.ofPattern(format));
    }

    public static LocalDateTime stringToLDT(String timeStr) {
        return stringToLDT(timeStr, DEFAULT_PATTERN);
    }

    public static String ldtToString(LocalDateTime localDateTime, String format) {
        return DateTimeFormatter.ofPattern(format).format(localDateTime);
    }

    public static String ldtToString(LocalDateTime localDateTime) {
        return ldtToString(localDateTime, DEFAULT_PATTERN);
    }

    public static Instant ldtToInstant(LocalDateTime localDateTime) {
        return localDateTime.atZone(ZoneId.systemDefault()).toInstant();
    }

    public static LocalDateTime instantToLDT(Instant instant) {
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

    /**
     * LocalDateTime转换为时间戳timestamp（毫秒值）
     *
     * @param localDateTime LocalDateTime时间
     * @return {@link long}
     * @date 2022/8/10 16:11
     * @author superC
     */
    public static Long ldtToTimestampMilli(LocalDateTime localDateTime) {
        return localDateTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
    }

    /**
     * 时间戳timestamp（毫秒值）转换为LocalDateTime
     *
     * @param timestampMilli 时间戳（毫秒值）
     * @return {@link LocalDateTime}
     * @date 2022/8/10 16:10
     * @author superC
     */
    public static LocalDateTime timestampMilliToLDT(long timestampMilli) {
        return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestampMilli), ZoneId.systemDefault());
    }

    /**
     * 时间戳timestamp转换为LocalDateTime
     *
     * @param timestamp 时间戳（秒值）
     * @return {@link LocalDateTime}
     * @date 2022/8/10 16:10
     * @author superC
     */
    public static LocalDateTime timestampToLDT(long timestamp) {
        return LocalDateTime.ofInstant(Instant.ofEpochSecond(timestamp), ZoneId.systemDefault());
    }

    /**
     * 将UTC时间转换为北京时间设置进去
     *
     * @param timeStr the text to parse such as "2007-12-03 10:15:30", not null
     * @return {@link Long}
     * @date 2023/2/28 14:01
     * @author superC
     */
    public static Long getTimestampOfDefault(String timeStr) {
        return ldtToTimestampMilli(stringToLDT(timeStr));
    }

    public static Instant getInstantOfDefault(String timeStr) {
        return ldtToInstant(stringToLDT(timeStr));
    }

    public static String getDateTimeOfTimestamp(long timestamp, String format) {
        return ldtToString(timestampMilliToLDT(timestamp), format);
    }

    public static String getDateTimeOfDefault(long timestamp) {
        return getDateTimeOfTimestamp(timestamp, DEFAULT_PATTERN);
    }


    public static String hourAddNum(String time, Integer hour) {
        //标准格式
        String s = "yyyy-MM-ddTHH:mm:ss.SSSZ";
        //若influxdb取得的时间长度小于标准长度
        if (time.length() < s.length()) {
            //若influxdb取得的时间无毫秒，即：yyyy-MM-ddTHH:mm:ssZ
            if (time.length() == 20) {
                time = time.substring(0, time.length() - 1) + ".000Z";
            } else {
                //若influxdb取得的时间有毫秒但长度不足，即：yyyy-MM-ddTHH:mm:ss.SZ或yyyy-MM-ddTHH:mm:ss.SSZ
                int n = s.length() - time.length();
                String sub = "";
                for (int i = 0; i < n; i++) {
                    sub += "0";
                }
                time = time.substring(0, time.length() - 1) + sub + 'Z';
            }
        }
        //若influxdb取得的时间长度大于标准长度
        if (time.length() > s.length()) {
            time = time.substring(0, s.length() - 1) + 'Z';
        }

        Date newTime = null;
        try {
            SimpleDateFormat format;

            if (time.contains(".")) {
                format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
            } else {
                format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss:SSS'Z'");
            }

            Date date = format.parse(time);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.HOUR_OF_DAY, hour);
            newTime = calendar.getTime();

            time = format.format(newTime);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return time;
    }

}